package com.shiguiwu.springmybatis.javabase.thread;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/**
 * @description: 循环
 * @author: stone
 * @date: Created by 2021/6/23 18:48
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.thread
 */
public class CyclicBarrierTests {

    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(10);
    //最后一个线程执行改函数
    private static CyclicBarrier cyclicBarrier2 = new CyclicBarrier(10,()->{
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("w我迟到了，哈哈哈");
    });

    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    public static class CyclicBarrierDemo implements Runnable {

        private String name;
        private int sleep;



        @Override
        public void run() {
            this.eat();
            this.drive();
        }

        void eat() {
            try {
                System.out.println("准备吃饭了======================>" + name);
                TimeUnit.SECONDS.sleep(sleep);
                //调用await()的时候，当前线程将会被阻塞，需要等待其他员工都到达await了才能继续
                cyclicBarrier2.await();
                System.out.println("开饭=======================>" + name);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        void drive() {
            try {
                System.out.println("准备开车了======================>" + name);
                TimeUnit.SECONDS.sleep(sleep);
                //调用await()的时候，当前线程将会被阻塞，需要等待其他员工都到达await了才能继续
                cyclicBarrier2.await();
                System.out.println("开车了=======================>" + name);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
           new  Thread(new CyclicBarrierDemo("t" + i, i)).start();
        }
    }
}
